# encoding: UTF-8

import os

def gen(packages, conf):
    if not os.path.exists(conf['htmlOutDir']):
        print 'htmlOutDir no  exists'
        exit(2)
    _initDir(conf)
    _copyFile(conf)

    navigation  = _genNavigation(packages, conf)
    detail      = _genDetail(packages, conf)

    template = open('./html/index_template.html', 'r')
    out      = open(conf['htmlOutDir'] + 'index.html', 'w')

    for line in template:
        if line.strip() == '${navigation}':
            line = navigation
        elif line.strip() == '${detail}':
            line = detail
        out.writelines(line)

    template.close()
    out.close()

def _initDir(conf):
    '''初始化 目录'''
    dir = conf['htmlOutDir']
    if not os.path.exists(dir + 'css'):
       os.mkdir(dir + 'css')
    if not os.path.exists(dir + 'js'):
        os.mkdir(dir + 'js')

def _copyFile(conf):
    cssList = os.listdir('./html/css')
    outDir     = conf['htmlOutDir']
    for file in cssList:
        open(outDir + 'css/' + file, 'wb').write(open('./html/css/' + file, 'rb').read())

    jsList = os.listdir('./html/js')
    for file in jsList:
        open(outDir + 'js/' + file, 'wb').write(open('./html/js/' + file, 'rb').read())

def _genNavigation(packages, conf):
    '''生成导航'''
    html = ''
    for pack in packages:
        comment  = pack['comment']
        packName = pack['package']
        baseUrl  = pack['baseURL']
        html += '<li  class="menu-title">' + comment + '</li>'
        for p in pack['protocls']:
            html += '<li class="menu-item"><a href="#' + packName + '_' + p['method'] + '">' +  p['method'] + '(' + p['comment'] + ')</a></li>'

    #生成Bean
    html += '<li  class="menu-title">Bean</li>'
    for pack in packages:
        beans = pack['beans']
        for bean in beans:
            html += '<li class="menu-item"><a href="#' + bean['name'] + '">' + bean['name'] + '</a></li>'

    return html

def _genDetail(packages, conf):
    '''生成接口描述'''

    # 获取全部Bean名称
    beans = {}
    for pack in packages:
        for bean in pack['beans']:
            beans[bean['name']] = bean['name']

    html = ''
    for pack in packages:
        packName = pack['package']
        baseUrl  = pack['baseURL']
        for p in pack['protocls']:
            html += '<h3 ><a name="'+ packName + '_' + p['method'] + '">' + p['comment'] + '</a></h3>'
            html += '<table class="table table-bordered">'
            html += '<tr><th colspan="3">接口地址:' + baseUrl + '/' + p['method'] + '</th></tr>'
            html += '<tr><td colspan="3">返回类型:' + _getType(beans, p['return']) + '</td></tr>'
            html += '<tr><td colspan="3">接口描述:' + p['comment'] +'</td></tr>'
            html += '<tr><td colspan="3">参数列表:</td></tr>'
            html += '<tr><td>参数名称</td><td>参数类型</td><td>参数描述</td></tr>'
            for param in p['params']:
                type = _getType(beans, param['type'])
                html += '<tr><td>' + param['name'] + '</td><td>' + type +'</td><td>' + param['comment'] + '</td></tr>'
            html += '</table>'

    #生成Bean
    for pack in packages:
        for bean in pack['beans']:
            html += '<h3 ><a name="' + bean['name'] + '">' + bean['name'] + '</a></h3>'
            html += '<table class="table table-bordered">'
            html += '<tr><th colspan="3">Bean名称:' + bean['name']
            if bean['extends']:
                html += '&nbsp;&nbsp;&nbsp;&nbsp;继承:<a href="#' + bean['extends'] + '">' + bean['extends'] + '</a>'
            html += '</th></tr>'
            html += '<tr><td colspan="3">接口描述:' + p['comment'] + '</td></tr>'
            html += '<tr><td colspan="3">属性列表:</td></tr>'
            html += '<tr><td>属性名称</td><td>属性类型</td><td>属性描述</td></tr>'
            for param in bean['params']:
                type = _getType(beans ,param['type'])
                html += '<tr><td>' + param['name'] + '</td><td>' + type + '</td><td>' + param['comment'] + '</td></tr>'
            html += '</table>'

    return html

def _getType(beans, type):
    newType = type
    if type.startswith("List"):
        name = type[5:-1]
        if beans.has_key(name):
            name = '<a href="#' + name + '">' + name + '<a>'
        newType = "List&lt;" + name + "&gt;"
    elif type.startswith("Map"):
        names = type[5:-1].split(",")
        if beans.has_key(names[0]):
            names[0] = '<a href="#' + names[0] + '">' + names[0] + '<a>'
        if beans.has_key(names[1]):
            names[1] = '<a href="#' + names[1] + '">' + names[1] + '<a>'
        newType = 'Map&lt;' + names[0] + ',' + names[1] + '&gt;'
    elif beans.has_key(type):
        newType = '<a href="#' + type + '">' + type + '<a>'

    return newType
